package com.baseweb.webadmin.core.util;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import org.apache.commons.lang.StringUtils;

import java.util.Random;

public class CommonUtil {

	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	public static final int SALT_SIZE = 8;

	private static  final String APP_NAME = "boyi-";
	private static final String ENTRYPT_SEED = "adcf1f5688c2802a8b19dee44f89588f";

	/**
	 * 
	 * sendMessage:向指定用户发送注册码验证短信. <br/>
	 * 适用条件:销售人员和库管员在注册的时候会向用户发送一个验证码,并使用注册短信模板.<br/>
	 * 注意:手机号码必须符合规范.<br/>
	 * 
	 * @author caodejun[caodejun@imimz.com]
	 * @param mobiles 接收短信的手机号码,如果多个则以英文逗号隔开
	 * @param smsParam 短信模板变量 - 短信内容 如:"{\"code\":\"" + code + "\",\"product\":\"五粮春\"}"
//	 * @param smsFreeSignName 短信签名
	 * @param smsTemplateCode 短信模板ID
	 * @return
	 * @since JDK 1.7
	 */
	public static boolean sendMessage(String mobiles, String smsParam,String smsTemplateCode) {
		TaobaoClient client = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest",
				ConfigUtil.getMsgAppKey(),
				ConfigUtil.getMsgAppSecret());
		AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();

		// 设置公共回传参数
		// req.setExtend("13547899969");
		// 设置短信类型，传入值请填写normal
		req.setSmsType(ConfigUtil.getSmsType());
		// 设置短信签名
		req.setSmsFreeSignName(ConfigUtil.getSmsFreeSignName());
		// 设置短信接收号码。支持单个或多个手机号码，传入号码为11位手机号码，不能加0或+86。群发短信需传入多个号码，以英文逗号分隔，一次调用最多传入200个号码。
		req.setRecNum(mobiles);
		// 设置短信模板ID，传入的模板必须是在阿里大鱼“管理中心-短信模板管理”中的可用模板。
		req.setSmsTemplateCode(smsTemplateCode);
		// 设置短信模板变量，传参规则{"key":"value"}，key的名字须和申请模板中的变量名一致，多个变量之间以逗号隔开。
		if (StringUtils.isNotBlank(smsParam)) {
			req.setSmsParam(smsParam);
		}
		AlibabaAliqinFcSmsNumSendResponse rsp = null;
		try {
			rsp = client.execute(req);
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return rsp.isSuccess();
	}

	/**
	 * 生成安全的密码，生成随机的16位salt并经过1024次 sha-1 hash
	 */
	public static String entryptPassword(String plainPassword) {
		String plain = Encodes.unescapeHtml(plainPassword);
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
		return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
	}

	/**
	 * 验证密码
	 * 
	 * @param plainPassword
	 *            明文密码
	 * @param password
	 *            密文密码
	 * @return 验证成功返回true
	 */
	public static boolean validatePassword(String plainPassword, String password) {
		String plain = Encodes.unescapeHtml(plainPassword);
		byte[] salt = Encodes.decodeHex(password.substring(0, 16));
		byte[] hashPassword = Digests.sha1(plain.getBytes(), salt, HASH_INTERATIONS);
		return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
	}

	/**
	 * 生成Token
	 */
	public static String generateToken(String entryptPassword) {
		String str = APP_NAME + entryptPassword + ENTRYPT_SEED;
		return Digests.md5(str);
	}

	/**
	 * 
	 * getRandomNum:获取一个随机的验证码. <br/>
	 * 适用条件:用户注册、提货、提现等需要用到手机验证码的地方.<br/>
	 * 
	 * @author caodejun[caodejun@imimz.com]
	 * @param size
	 * @return
	 * @since JDK 1.7
	 */
	public static String getRandomNum(int size) {
		StringBuilder sb = new StringBuilder();
		String no = "0123456789";
		for (int i = 0; i < size; i++) {
			int index = (int) (Math.random() * 10);
			sb.append(no.charAt(index));
		}
		return sb.toString();
	}

	public static String getRandomString(int length) {

		String val = "";
		Random random = new Random();

		//参数length，表示生成几位随机数
		for(int i = 0; i < length; i++) {

			String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
			//输出字母还是数字
			if( "char".equalsIgnoreCase(charOrNum) ) {
				//输出是大写字母还是小写字母
				int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
				val += (char)(random.nextInt(26) + temp);
			} else if( "num".equalsIgnoreCase(charOrNum) ) {
				val += String.valueOf(random.nextInt(10));
			}
		}
		return val;
	}


	public static Integer[] getBizCredit(int credits){
		Integer result[] = new Integer[5];
		result[0] = credits/2500;

		result[1] = (credits-2500*result[0])/500;

		result[2] = (credits-2500*result[0]-500*result[1])/100;

		result[3] = (credits-2500*result[0]-500*result[1]-100*result[2])/10;

		result[4] = credits-2500*result[0]-500*result[1]-100*result[2]-10*result[3];

		return result;
	}

	public static String getBizCreditFlag(Integer credits){
		if (credits == null || credits.intValue() == 0){
			return "";
		}

		StringBuffer sb = new StringBuffer();
		Integer ct[] = getBizCredit(credits);

		for (int i = 0; i < ct.length; i++) {
			sb.append(getFlagStr(i, ct[i]));
		}

		return sb.toString();
	}

	private static String getFlagStr(int index, int count){
		StringBuffer sb = new StringBuffer();

		String icon = "";
		String iconName = "";
		switch (index)
		{
			case 0:
				icon = "level_prime.png";
				iconName = "至尊";
				break;
			case 1:
				icon = "level_crown.png";
				iconName = "皇冠";
				break;
			case 2:
				icon = "level_gem.png";
				iconName = "钻石";
				break;
			case 3:
				icon = "level_star.png";
				iconName = "星星";
				break;
			case 4:
				icon = "level_flag.png";
				iconName = "红旗";
				break;
		}

		for (int i = 0; i < count; i++) {
			sb.append("<img src=\"/common/icon/"+icon+"\" width=\"20px\" height=\"20px\" alt=\""+iconName+"\"/>");
		}

		return sb.toString();
	}

	public static void main(String[] args) {
		Integer result[] = getBizCredit(1000);
		for (int i = 0; i < 5; i++) {
			System.out.println(result[i]);
		}
		System.out.println(getBizCreditFlag(1000));
//		System.out.println("----------");
//		Integer result1[] = getBizCredit(200);
//		for (int i = 0; i < 5; i++) {
//			System.out.println(result1[i]);
//		}
//		System.out.println("----------");
//		Integer result2[] = getBizCredit(15);
//		for (int i = 0; i < 5; i++) {
//			System.out.println(result2[i]);
//		}
	}
}
